package com.elinkway.infinitemovies.adapter;

import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnKeyListener;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.text.TextUtils;
import android.util.SparseArray;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.ToggleButton;

import com.elinkway.infinitemovies.application.MoviesApplication;
import com.elinkway.infinitemovies.bean.PlayRecord;
import com.elinkway.infinitemovies.config.SettingManage;
import com.elinkway.infinitemovies.dao.DownLoadPlayRecordDao;
import com.elinkway.infinitemovies.download.ContainSizeManager;
import com.elinkway.infinitemovies.download.DownloadEntity;
import com.elinkway.infinitemovies.download.DownloadHelper;
import com.elinkway.infinitemovies.download.DownloadInfo;
import com.elinkway.infinitemovies.download.DownloadJob;
import com.elinkway.infinitemovies.download.DownloadUtils;
import com.elinkway.infinitemovies.ui.activity.DownloadJobActivity;
import com.elinkway.infinitemovies.utils.LogUtils;
import com.elinkway.infinitemovies.utils.MoviesUtils;
import com.elinkway.infinitemovies.utils.NetWorkTypeUtils;
import com.elinkway.infinitemovies.utils.StringUtil;
import com.elinkway.infinitemovies.utils.ToastUtil;
import com.elinkway.infinitemovies.utils.UmengEventPoster;
import com.elinkway.infinitemovies.utils.Utils;
import com.le123.ysdq.R;
import com.nostra13.universalimageloader.core.ImageLoader;

import java.util.ArrayList;

/**
 * 正在缓存列表 适配器
 */

public class DownloadJobAdapter extends SparseArrayAdapter<DownloadJob> {
    public boolean deleteState;
    public ArrayList<Boolean> mChecked;
    public int deletedNum;
    private DownloadJobActivity DownloadJobActivity;
    private LayoutInflater mInflater;
    private int mFromWhere;
    private String taskstate;
    public ContainSizeManager mSizeManager;
    //获取是否允许3g下载的用户选择数据
    private SettingManage mSettingManage;
    private SharedPreferences mSettingSharePreference;
    private Editor mSettingPreferenceEditor;
    private DownLoadPlayRecordDao downloadPlayRecord;

    public DownloadJobAdapter(SparseArray<DownloadJob> mList, DownloadJobActivity mContext, int fromWhere) {
        super(mList, mContext);
        DownloadJobActivity = mContext;
        downloadPlayRecord = DownLoadPlayRecordDao.getInstance(mContext);
        mInflater = mContext.getLayoutInflater();
        mChecked = new ArrayList<Boolean>();
        mFromWhere = fromWhere;
        for (int i = 0; i < MoviesApplication.getInstance().getDownloadManager().getAllDownloads().size(); i++) {
            mChecked.add(false);
        }
        mSizeManager = new ContainSizeManager(mContext);
        mSettingManage = new SettingManage(mContext);
        mSettingSharePreference = mContext.getSharedPreferences(SettingManage.SETTING_RELATIVE_SHAREPREFERENCE, Context.MODE_PRIVATE);
        mSettingPreferenceEditor = mSettingSharePreference.edit();
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder = null;
        if (convertView == null) {
            holder = new ViewHolder();
            convertView = mInflater.inflate(R.layout.download_row, null);

            holder.imgUrlIv = (ImageView) convertView.findViewById(R.id.left_image_iv);
            holder.coverLayerIv = (ImageView) convertView.findViewById(R.id.cover_layer_iv);
            holder.downloadName = (TextView) convertView.findViewById(R.id.downloadName);
            holder.downloadLength = (TextView) convertView.findViewById(R.id.downloadLength);
            holder.progressText = (TextView) convertView.findViewById(R.id.rowProgress);
            holder.progressBar = (ProgressBar) convertView.findViewById(R.id.ProgressBar);
            holder.rlDownLayout = (RelativeLayout) convertView.findViewById(R.id.videolayout_new);
            holder.btnDelete = (ToggleButton) convertView.findViewById(R.id.btnDelete);
            holder.folderBg = (LinearLayout) convertView.findViewById(R.id.iv_folder);
            holder.downloadSegmentNumber = (TextView) convertView.findViewById(R.id.downloadSegmentNumber);
            holder.ifwatch = (ImageView) convertView.findViewById(R.id.ifwatch);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }
        holder.ifwatch.setVisibility(View.GONE);
        if (null != mList) {
            DownloadJob job = null;
            if (position < mList.size() && mList.valueAt(position) instanceof DownloadJob) {
                job = mList.valueAt(position);
            }

            if (null != job) {
                DownloadEntity entity = job.getEntity();

                holder.folderBg.setVisibility(View.GONE);
                if (null != entity) {
                    if(!TextUtils.isEmpty(entity.getImgUrl())){
                        ImageLoader.getInstance().displayImage(entity.getImgUrl(), holder.imgUrlIv);
                    }else{
                        holder.imgUrlIv.setImageResource(R.drawable.ic_launcher);
                    }
                    holder.downloadName.setText(entity.getDisplayName());
                    if (job.getStreamList() != null && job.getStreamList().size() > 1) {
                        (convertView.findViewById(R.id.linearLayPlaySegment)).setVisibility(View.VISIBLE);
                        holder.downloadSegmentNumber.setVisibility(View.VISIBLE);
                        holder.downloadSegmentNumber.setText(mContext.getString(R.string.download_segment, String.valueOf(job.getCurrentDownloadPiece() + 1), job.getStreamList().size()));
                    } else if (job.getStreamList() != null && job.getStreamList().size() == 1) {
                        (convertView.findViewById(R.id.linearLayPlaySegment)).setVisibility(View.GONE);
                    }

                }
                if (job.getStatus() == DownloadJob.DOWNLOADING || job.getStatus() == DownloadJob.COMPLETE) {
                    if (DownloadInfo.MP4.equals(entity.getDownloadType())) {
                        holder.downloadLength.setText(DownloadUtils.getDownloadedSize(job.getDownloadedSize()) + "MB/" + DownloadUtils.getTotalSize(job.getTotalSize()) + "MB");
                        holder.downloadLength.setTextColor(DownloadJobActivity.getResources().getColor(R.color.color_666666));
                        holder.downloadLength.setVisibility(View.VISIBLE);
                    } else {
                        holder.downloadLength.setText(mContext.getString(R.string.compulate_size));
                        holder.downloadLength.setTextColor(DownloadJobActivity.getResources().getColor(R.color.color_666666));
                        (convertView.findViewById(R.id.linearLayPlaySegment)).setVisibility(View.GONE);
                    }
                } else {
                    holder.downloadSegmentNumber.setVisibility(View.INVISIBLE);
                }
                if (job.getProgress() == 100) {
                    if (!"true".equals(job.getEntity().getIfWatch())) {
                        holder.ifwatch.setVisibility(View.VISIBLE);
                    } else {
                        holder.ifwatch.setVisibility(View.GONE);
                    }
                    downloadJobCompleted(holder, entity, position, job);
                    taskstate = "finished";
                    String name = job.getEntity().getMedianame();
                    String albumID = job.getEntity().getMid();
                    String vid = job.getEntity().getId();
                    UmengEventPoster.postDownLoadStateClick(name, albumID, vid, taskstate);
                } else {
                    downloadJobUnCompleted(holder, job, position);
                    switch (job.getStatus()) {
                        case DownloadJob.INIT:
                            holder.coverLayerIv.setImageResource(R.drawable.download_init_img);
                            holder.coverLayerIv.setVisibility(View.VISIBLE);
                            break;
                        case DownloadJob.DOWNLOADING:
                            holder.coverLayerIv.setVisibility(View.GONE);
                            break;
                        case DownloadJob.NO_USER_PAUSE:
                        case DownloadJob.PAUSE:
                            holder.progressText.setText(DownloadJobActivity.getString(R.string.parentheses_inside_txt, "已暂停"));
                            showExceptionPause(holder, job);
                            if (job.getExceptionType() == DownloadJob.DOWNLOAD_FAILUER) {
                                taskstate = "failed";
                                holder.downloadLength.setText("下载失败，点击重试");
                                holder.downloadLength.setTextColor(DownloadJobActivity.getResources().getColor(R.color.red_f9362a));
                                holder.downloadLength.setVisibility(View.VISIBLE);
                            } else {
                                holder.coverLayerIv.setImageResource(R.drawable.download_pause_img);
                                holder.coverLayerIv.setVisibility(View.VISIBLE);
                                downloadJobUnCompletedPause(holder, job, position);
                            }
                            break;
                        case DownloadJob.WAITING:
                            holder.progressText.setText(DownloadJobActivity.getString(R.string.parentheses_inside_txt, "等待中"));
                            holder.coverLayerIv.setImageResource(R.drawable.download_waitting_img);
                            holder.coverLayerIv.setVisibility(View.VISIBLE);
                            break;
                        default:
                            holder.coverLayerIv.setVisibility(View.GONE);
                            break;
                    }
                }
            }
            convertView.setOnClickListener(new DownloadControlListener(job, holder, position));
        }

        return convertView;
    }

    private void downloadJobUnCompleted(ViewHolder holder, DownloadJob job, int position) {
        holder.progressText.setVisibility(View.VISIBLE);
        holder.progressBar.setVisibility(View.VISIBLE);
        holder.progressBar.setProgressDrawable(DownloadJobActivity.getResources().getDrawable(R.drawable.progress_style_download));
        holder.progressBar.setMax(100);
        holder.progressBar.setProgress(job.getProgress());
        holder.progressText.setText(DownloadJobActivity.getString(R.string.parentheses_inside_txt, job.getRate()));
        deleteStateHandler(holder, position);
    }

    private void downloadJobUnCompletedPause(ViewHolder holder, DownloadJob job, int position) {
        holder.progressBar.setVisibility(View.VISIBLE);
        holder.progressBar.setProgressDrawable(DownloadJobActivity.getResources().getDrawable(R.drawable.progress_style_download_pause));
        holder.progressBar.setMax(100);
        holder.progressBar.setProgress(job.getProgress());
    }

    //下载完成的页面显示与处理
    private void downloadJobCompleted(ViewHolder holder, DownloadEntity entity, int position, DownloadJob job) {
        holder.progressBar.setVisibility(View.GONE);
        holder.progressText.setVisibility(View.GONE);
        holder.downloadSegmentNumber.setVisibility(View.GONE);
        if (null != entity) {
            if (DownloadHelper.getDownloadedFileSize(entity, entity.getPath()) == 0) {
                holder.downloadLength.setText("已完成" + "/" + mContext.getString(R.string.file_has_been_removed));
                holder.downloadLength.setTextColor(DownloadJobActivity.getResources().getColor(R.color.color_666666));
            } else {
                if (DownloadInfo.M3U8.equals(entity.getDownloadType())) {
                    if (entity.getFileSize() < 1024 * 1024) {
                        entity.setFileSize(DownloadHelper.getDownloadedFileSize(entity, entity.getPath()));
                    }
                    holder.downloadLength.setText(DownloadUtils.getTotalSize(entity.getFileSize()) + "MB");
                    holder.downloadLength.setTextColor(DownloadJobActivity.getResources().getColor(R.color.color_666666));
                } else {
                    holder.downloadLength.setText(DownloadUtils.getTotalSize(DownloadHelper.getDownloadedFileSize(entity, entity.getPath())) + "MB");
                    holder.downloadLength.setTextColor(DownloadJobActivity.getResources().getColor(R.color.color_666666));
                }
            }
            PlayRecord playRecord = downloadPlayRecord.getByAidAndPorder(entity.getMid(), entity.getPorder());
            if(playRecord != null){
                holder.progressText.setText(DownloadJobActivity.getString(R.string.vertical_line_record, MoviesUtils.seekHistroyTimeFormat(playRecord.getSeekHistory(), mContext)));
                holder.progressText.setVisibility(View.VISIBLE);
            }else{
                holder.progressText.setVisibility(View.GONE);
            }
        }
        deleteStateHandler(holder, position);
    }

    // 设置下载选中项
    public void setDeleteItem(int position, View view) {
        ViewHolder viewHolder = (ViewHolder) view.getTag();
        ToggleButton deleteBtn = (ToggleButton) viewHolder.btnDelete;

        if (null != mList) {
            DownloadJob job = null;
            if (position < mList.size() && mList.valueAt(position) instanceof DownloadJob) {
                job = mList.valueAt(position);
            }

            if (null != job) {
                if (job.getCheck()) {
                    deleteBtn.setBackgroundDrawable(DownloadJobActivity.getResources().getDrawable(R.drawable.pic_localvideo_uncheck));
                    deletedNum--;
                    job.setCheck(false);
                } else {
                    deleteBtn.setBackgroundDrawable(DownloadJobActivity.getResources().getDrawable(R.drawable.pic_localvideo_checked));
                    deletedNum++;
                    job.setCheck(true);
                }
            }

        }
        DownloadJobActivity.setTitle();
    }

    private class DownloadControlListener implements OnClickListener {
        private final DownloadJob job;
        private final ViewHolder holder;
        private int position;

        private DownloadControlListener(DownloadJob job, ViewHolder holder, int position) {
            this.job = job;
            this.holder = holder;
            this.position = position;
        }

        @Override
        public void onClick(View v) {
            if(deleteState){
                setDeleteItem(position, v);
                if (deletedNum != getCount()) {
                    DownloadJobActivity.mUserDeletecount.setText(R.string.check_all);
                } else {
                    DownloadJobActivity.mUserDeletecount.setText(R.string.deselect_all);
                }
            } else {
                if (job.getProgress() == 100) {
                    if (DownloadHelper.getPath(job.getEntity(), job.getEntity().getPath()) == null || DownloadHelper.getDownloadedFileSize(job.getEntity(), job.getEntity().getPath()) == 0) {
                        ToastUtil.showLongToast(DownloadJobActivity, R.string.file_has_been_removed);
                        return;
                    }

                    DownloadJobActivity.mDownloadManager.playVideoList(DownloadJobActivity.getCompletedJobList(), job, DownloadJobActivity.title.getText().toString());
                    DownloadJobActivity.mDownloadManager.notifyObservers();
                } else {
                    taskstate = "";
                    switch (job.getStatus()) {
                        case DownloadJob.NO_USER_PAUSE:
                        case DownloadJob.PAUSE:
                            if (mSizeManager.getFreeSize() > Utils.SDCARD_MINSIZE) {//sd卡容量大于100m，可以添加
                                popIfContinueDownloadDialog();
                                taskstate = "download";
                                holder.coverLayerIv.setImageResource(R.drawable.download_init_img);
                                holder.coverLayerIv.setVisibility(View.VISIBLE);
                            } else {
                                ToastUtil.showShortToast(DownloadJobActivity, R.string.sdcard_nospace);
                            }
                            break;
                        case DownloadJob.WAITING:
                            job.cancel();
                            holder.progressText.setText(DownloadJobActivity.getString(R.string.parentheses_inside_txt, "已暂停"));
                            holder.coverLayerIv.setImageResource(R.drawable.download_pause_img);
                            holder.coverLayerIv.setVisibility(View.VISIBLE);
                            break;
                        case DownloadJob.DOWNLOADING:
                            boolean userPause = job.pauseByUser();
                            LogUtils.d(Utils.DOWN_TAG, "!!!!!!!!!!!!DownLoadJobAdapter class!!!!!!!!!!!!");
                            LogUtils.d(Utils.DOWN_TAG, "!!!!!!!!!!!!!!user pause and cancle mDownloadTask result is " + userPause);
                            holder.progressText.setText(DownloadJobActivity.getString(R.string.parentheses_inside_txt, "已暂停"));
                            taskstate = "pausedbyuser";
                            holder.coverLayerIv.setImageResource(R.drawable.download_pause_img);
                            holder.coverLayerIv.setVisibility(View.VISIBLE);
                            break;
                    }
                    String name = job.getEntity().getMedianame();
                    String albumID = job.getEntity().getMid();
                    String vid = job.getEntity().getId();
                    UmengEventPoster.postDownLoadStateClick(name, albumID, vid, taskstate);
                }
            }
        }

        private void popIfContinueDownloadDialog() {
            if (NetWorkTypeUtils.reportNetType(DownloadJobActivity) == 2 && !job.isDownloadcan3g()) {
                if (job.isCurrentPathExist()) {
                    checkIfContinueDownloadDialog();
                }
            } else {
                start(job, holder);
            }
        }

        private void checkIfContinueDownloadDialog() {
            Builder customBuilder = new Builder(DownloadJobActivity);
            customBuilder
                    .setTitle(R.string.tip)
                    .setMessage(R.string.wireless_tip)
                    .setPositiveButton(R.string.continue_download,
                            new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog,
                                                    int which) {
                                    mSettingManage.setToggleButtonPreference(true, mSettingPreferenceEditor, SettingManage.IS_DOWNLOAD_CAN_3G);
                                    start(job, holder);
                                    dialog.dismiss();
                                }
                            })
                    .setNegativeButton(R.string.pause_download,
                            new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog,
                                                    int which) {
                                    dialog.dismiss();
                                }
                            })
                    .setOnKeyListener(new OnKeyListener() {
                        @Override
                        public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                            if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
                                dialog.dismiss();
                            }
                            return false;
                        }
                    });
            Dialog dialog = customBuilder.create();
            dialog.show();
        }
    }

    private void deleteStateHandler(ViewHolder holder, int position) {
        if (deleteState) {
            holder.btnDelete.setBackgroundDrawable(DownloadJobActivity.getResources().getDrawable(R.drawable.pic_localvideo_uncheck));
            holder.btnDelete.setVisibility(View.VISIBLE);

            if (null != mList) {
                DownloadJob job = null;
                if (position < mList.size() && mList.valueAt(position) instanceof DownloadJob) {
                    job = mList.valueAt(position);
                }

                if (null != job) {
                    if (job.getCheck()) {
                        holder.btnDelete.setBackgroundDrawable(DownloadJobActivity.getResources().getDrawable(R.drawable.pic_localvideo_checked));
                    } else {
                        holder.btnDelete.setBackgroundDrawable(DownloadJobActivity.getResources().getDrawable(R.drawable.pic_localvideo_uncheck));
                    }
                }
            }

        } else {
            holder.btnDelete.setVisibility(View.GONE);
        }
    }

    public void start(DownloadJob job, ViewHolder holder) {
        if (!job.isCurrentPathExist()) {
            sdcardChangeDialog(mContext, job, holder);
        } else {
            if (null != job && null != job.getEntity()) {
                if (TextUtils.isEmpty(job.getEntity().getPath()) && !TextUtils.isEmpty(job.getmDestination())) {
                    job.getEntity().setPath(job.getmDestination());
                }
                job.start();
                if (null != holder) {
                    holder.progressText.setText(DownloadJobActivity.getString(R.string.parentheses_inside_txt, "0.0KB/s"));
                }
            }
        }
    }

    private void showExceptionPause(final ViewHolder holder,
                                    final DownloadJob job) {
        if (job.getExceptionType() == DownloadJob.NET_SHUT_DOWN)
            holder.progressText.setText(mContext.getString(R.string.parentheses_inside_txt, mContext.getString(R.string.net_shutdown)));
        if (job.getExceptionType() == DownloadJob.NO_SD)
            holder.progressText.setText(mContext.getString(R.string.parentheses_inside_txt, mContext.getString(R.string.no_sdcard_added)));
        if (job.getExceptionType() == DownloadJob.SD_SPACE_FULL)
            holder.progressText.setText(mContext.getString(R.string.parentheses_inside_txt, mContext.getString(R.string.no_space_tip)));
        if (job.getExceptionType() == DownloadJob.FILE_NOT_FOUND)
            holder.progressText.setText(mContext.getString(R.string.parentheses_inside_txt, mContext.getString(R.string.no_sdcard_added)));
        if (job.getExceptionType() == DownloadJob.DOWNLOAD_FAILUER)
            holder.progressText.setText(mContext.getString(R.string.parentheses_inside_txt, mContext.getString(R.string.download_faile)));
    }

    private class ViewHolder {
        ImageView imgUrlIv;     //视频的图片
        ImageView coverLayerIv;
        TextView downloadName; //文件名,如xxxx第几集
        TextView downloadLength;//大小：15M/88M
        TextView progressText;//网速/下载中/暂停中/等待中/
        ProgressBar progressBar;//进度条
        RelativeLayout rlDownLayout;//整个一个item，用于奇偶变色
        ToggleButton btnDelete;//删除按钮
        Button btnPlay;//播放按钮
        LinearLayout folderBg;
        TextView downloadSegmentNumber; // 视频段数
        ImageView ifwatch;//是否观看过
    }

    public void sdcardChangeDialog(Context context, final DownloadJob dJob, final ViewHolder holder) {
        if (null == context) {
            return;
        }
        String newPath = DownloadHelper.getDownloadPath();
        if (!StringUtil.isEmpty(newPath) && newPath.contains("/" + Utils.getDownLoadFolder())) {
            newPath = newPath.substring(0, newPath.indexOf("/" + Utils.getDownLoadFolder()));
        }
        if (newPath.equals(dJob.getmDestination())) {
            newPath = Utils.SAVE_FILE_PATH_DIRECTORY;
            newPath = newPath.substring(0, newPath.indexOf("/" + Utils.getDownLoadFolder()));
        }
        Builder customBuilder = new Builder(context);
        customBuilder
                .setTitle(R.string.tip)
                .setMessage(context.getString(R.string.sd_change_message_before) + dJob.getmDestination()
                        + context.getString(R.string.sd_change_message_middle)
                        + newPath + context.getString(R.string.sd_change_message_after))
                .setPositiveButton(R.string.ok,
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog,
                                                int which) {
                                DownloadJob job = dJob;
                                job.setmDestination(DownloadHelper.getDownloadPath());
                                job.getEntity().setPath(DownloadHelper.getDownloadPath());
                                MoviesApplication.getInstance().getDownloadManager().getProvider().updateDownloadEntity(job);
                                start(job, holder);
                                dialog.dismiss();
                            }
                        })
                .setNegativeButton(R.string.cancel,
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog,
                                                int which) {
                                dialog.dismiss();
                            }
                        })
                .setOnKeyListener(new OnKeyListener() {
                    @Override
                    public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
                            dialog.dismiss();
                        }
                        return false;
                    }
                });
        Dialog dialog = customBuilder.create();
        dialog.show();
    }
}
